package com.coco.dao.Impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.coco.dao.UserDao;
import com.coco.model.User;
import com.coco.utils.C3P0Util;
import com.coco.utils.Hibernate;

public class UserDaoImpl implements UserDao {

	@Override
	public int register(String sql, Object...params) throws SQLException {
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		return qr.update(sql,params);
			
	}

	@Override
	public User findByName(String uname) throws SQLException {
		String sql = "select * from user where uname=?";
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		return qr.query(sql, new BeanHandler<>(User.class),uname);
	}

	public List<User> findByOthers(String sql, Object...params) throws SQLException {
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		return qr.query(sql, new BeanListHandler<>(User.class),params);
			
	}
	
	@Override
	public int update(String sql, Object... params) throws SQLException {
		QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
		//TODO
		return qr.update(sql, params);
			
	}

	@Override
	public User findByNameAndPwd(String uname, String upwd) throws SQLException {
		String sql = "select * from user where uname=? and upwd=?";
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		return qr.query(sql, new BeanHandler<>(User.class),uname,upwd);
			
	}

	@Override
	public void add(User user){
		Session session = Hibernate.getCurrentSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		
		session.save(user);
		
		if(session != null){
			transaction.commit();
			session.close();
		}
	}
}

	